import mongoose, { Promise } from 'mongoose'
// 修复了报错，将相关重复错误记录删除
export const correct_error = async (ctx, next) => {
  const  { funcName,_id,is_batch,errCont} = ctx.query
  const errLog = mongoose.model('errLog')
  let res_remove = {}
  // 可选择删除单个id或者删除多条同样报错误内容
  if(+is_batch === 1){
    res_remove =  await errLog.remove({errCont:errCont,status:0})
  } else {
    res_remove =  await errLog.remove({_id:_id})
  }
  // 新增一条已解决的记录
  await sign_err_log({funcName,errCont,status:1,happenCount:res_remove.n})
  ctx.body = {
    state: 401,
    data:res_remove
  }
  next()
}
export const get_err_log = async (ctx, next) => {
 
 let { page_size = 10,page=1} = ctx.query
 page_size = +page_size
 page = +page
 
  let status = ctx.query.status
  let data = {}
  const errLog = mongoose.model('errLog')
  // const remove =  await errLog.remove({})
  const count =  await errLog.count()
  // console.log('e发火速恢复是对方',count,remove,'e发火速恢复是对方1')
  if(status){
    data = await errLog.find({status:status}).sort({"createdAt":1}).skip(page_size*(page-1)).limit(page_size)
  }else{
    data = await errLog.find().sort({"createdAt":1}).skip(page_size*(page-1)).limit(page_size)
  }
  ctx.body = {
    state: 401,
    data:{
      total:count,
      list:data
    }
  }
  next()
}
// 记录错误日志数据
export const input_err_log = async  (ctx, next) => {
  // 放入数据库
  await sign_err_log(ctx.query)
  ctx.body = {
    state: 401,
    data: 'ok'
  }
  console.log('写入完毕')
  next()
}
// 错误日志数据放入数据库
export const sign_err_log =(query) => {
  
  return new Promise(async (resolve) => {
    const {funcName,errCont,status,allCont='',happenCount=1} = query
    const errLog = mongoose.model('errLog')
    let sing_errLog = new errLog({
      funcName: funcName, // 发生错误的函数
      errCont: errCont, // 错误内容
      status: status, // 是否已解决
      allCont: allCont,
      happenCount: happenCount,
    })
    await sing_errLog.save();
    resolve()
  })
}